package com.qulai.quartz.task;

import com.qulai.amazon_us.domain.amazon_us.AmazonUsRecord;
import com.qulai.amazon_us.mapper.amazon_us.AmazonUsRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component("replacePythonDef")
public class ReplacePythonDef {


    @Autowired
    private AmazonUsRecordMapper amazonUsRecordMapper;


    private static final Logger log = LoggerFactory.getLogger(ReplacePythonDef.class);


    public void clearFailUploadRecordOrAddRecord(String directoryPath, Integer intervalDay, String deleteStr) {
        if (directoryPath == null || directoryPath.isEmpty()) {
            directoryPath = "\\\\CENTER\\center\\file\\amazon_report";
        }
        if (intervalDay == null || intervalDay < 0) {
            intervalDay = 3;
        }
        if (deleteStr == null || deleteStr.isEmpty()) {
            deleteStr = "No";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取三天前的日期时间并格式化为字符串
        String intervalDayDateTimeStr = LocalDateTime.now().minusDays(intervalDay).format(formatter);
        // 获取指定文件夹下的所有txt文件
        File folder = new File(directoryPath);
        File[] files = folder.listFiles((dir, name) -> name.endsWith(".txt"));

        if (files != null) {
            for (File file : files) {
                try {
                    // 获取去后缀的文件名
                    String filename = file.getName().replace(".txt", "");
                    // 读取文件内容并处理
                    Map<String, String> skuAsinMap = readInventoryFile(file);
                    // 读取数据库内容
                    String recordTableName = "amazon_us_record_"+ filename.toLowerCase();

                    boolean isTableExists =  amazonUsRecordMapper.tableExists(recordTableName);
                    if(!isTableExists){
                         continue;
                    }

                    List<AmazonUsRecord> amazonUsRecords = amazonUsRecordMapper.selectAmazonUsRecordListByShop_v2(recordTableName, intervalDayDateTimeStr);
                    Map<String, Long> skuIdDbMap = new HashMap<>();
                    if (!amazonUsRecords.isEmpty()) {
                        skuIdDbMap = amazonUsRecords.stream()
                                .collect(Collectors.toMap(
                                        AmazonUsRecord::getSku,
                                        AmazonUsRecord::getId, (existing, replacement) -> replacement
                                ));
                    }
                    // 判断并分组
                    List<String> missingSkus = new ArrayList<>();
                    List<String> existingSkus = new ArrayList<>();
                    skuIdDbMap.forEach((sku, id) -> {
                        if (skuAsinMap.containsKey(sku)) {
                            existingSkus.add(sku);
                        } else {
                            missingSkus.add(sku);
                        }
                    });
                    //更新存在的放入asin
                    List<AmazonUsRecord> need_update = new ArrayList<>();
                    for (String sku : existingSkus) {
                        Long id = skuIdDbMap.get(sku);
                        if (id != null) {
                            AmazonUsRecord tmp = new AmazonUsRecord();
                            tmp.setId(id);
                            tmp.setAsin(skuAsinMap.getOrDefault(sku, ""));
                            need_update.add(tmp);
                        }
                    }
                    if (!need_update.isEmpty()) {
                        int batchSize = 2000;  // 每批次更新2000条
                        List<AmazonUsRecord> updateList = new ArrayList<>(need_update);

                        for (int i = 0; i < updateList.size(); i += batchSize) {
                            int end = Math.min(i + batchSize, updateList.size());
                            List<AmazonUsRecord> batch = updateList.subList(i, end);
                            amazonUsRecordMapper.batchUpdateAsin_v2(recordTableName,batch);
                            try {
                                Thread.sleep(300);  // 300ms间隔
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                            }
                        }
                    }
                    //删除,亚马逊不存在的
                    if ("Yes".equals(deleteStr)) {
                        List<Long> need_delete = new ArrayList<>();
                        for (String sku : missingSkus) {
                            Long id = skuIdDbMap.get(sku);
                            if (id != null) {
                                need_delete.add(id);
                            }
                        }
                        if (!need_delete.isEmpty()) {
                            int batchSize = 2000;  // 每批次删除2000条
                            List<Long> idList = new ArrayList<>(need_delete);
                            for (int i = 0; i < idList.size(); i += batchSize) {
                                int end = Math.min(i + batchSize, idList.size());
                                List<Long> batchIds = idList.subList(i, end);
                                Long[] ids = batchIds.toArray(new Long[0]);
                                amazonUsRecordMapper.deleteAmazonUsRecordByIds_v2(recordTableName,ids);
                                try {
                                    Thread.sleep(300);  // 300ms间隔
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                }
                            }
                        }
                    }

                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    // 读取文件并构建skuAsinMap
    private static Map<String, String> readInventoryFile(File file) throws IOException {
        Map<String, String> skuAsinMap = new HashMap<>();
        // 使用BufferedReader读取文件
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }
                String[] parts = line.split("\t");
                if (parts.length >= 2) {
                    String sku = parts[0].trim();
                    String asin = parts[1].trim();
                    skuAsinMap.put(sku, asin);
                }
            }
        }
        return skuAsinMap;
    }

}
